import Dep from "./dep";

// 定义Observer类，用于实现数据劫持
export default class Observer {
    constructor(data) {
        this.data = data;
        this.walk(this.data)
    }

    walk(data) {
        if (!data || typeof data !== "object") {
            return;
        }
        Object.keys(data).forEach((key) => {
            this.defineReactive(data, key, data[key])
        })
    }

    defineReactive(data, key, value) {
        var dep = new Dep();
        // defineProperty定义属性的对象，拦截对属性的访问和修改
        Object.defineProperty(data, key, {
            enumerable: true,
            configurable: false,
            get: () => {
                Dep.target && dep.addSub(Dep.target);
                return value;
            },
            // 更新
            set: (newValue) => {
                value = newValue;
                dep.notify();
            }
        })
        this.walk(value)
    }
}